package com.wshl.aijiuunion.controller.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wshl.aijiuunion.BaseActivity;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.MainActivity;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.bean.AlipayBean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.utils.PayResult;
import com.wshl.aijiuunion.view.bean.WxPayBean;
import com.wshl.aijiuunion.view.widget.Keyboard;
import com.wshl.aijiuunion.view.widget.Loadingdialog;
import com.wshl.aijiuunion.view.widget.PayEditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.wshl.aijiuunion.view.widget.Loadingdialog.dialog;

/**
 * Created by Administrator on 2018/11/20.
 */

public class WebActivity extends BaseActivity {


    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;

    @BindView(R.id.ll_web)
    LinearLayout llWeb;
    @BindView(R.id.img_back)
    ImageView imgBack;
    private AgentWeb mAgentWeb;
    private WebView webView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        String weburl = getIntent().getStringExtra(GlobConstant.WEBURL);
        // String webtitle = getIntent().getStringExtra(GlobConstant.WEBTITLE);
        if (TextUtils.isEmpty(weburl)) {
            ToastUtils.showLong("参数错误");
            return;
        }

        //Loadingdialog.show(this);
        //   tvTopTitle.setText(webtitle);
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent((LinearLayout) llWeb, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator(getResources().getColor(R.color.theme), 2)
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewcLient)
                .createAgentWeb()
                .ready()
                .go(weburl);
        // .go("http://www.baidu.com");
        // .go("http://safe.wsstreet.net/h5/#/old_car?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9zYWZlLndzc3RyZWV0Lm5ldFwvYXBpXC9sb2dpbiIsImlhdCI6MTU2Njg5NjQ4MCwiZXhwIjoxNTY3NDk2NDgwLCJuYmYiOjE1NjY4OTY0ODAsImp0aSI6ImY2Z2JxTDBQa0hBUDEwRUQiLCJzdWIiOjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEiLCJndWFyZCI6ImFwaSJ9.hFFDOB2I45PBr9Yy8uckRq6T4hH55QIJS9wT4K6y8NE&cities_id=151&lat=34.82259&lon=113.564587");

        webView = mAgentWeb.getWebCreator().getWebView();
        // 限制在WebView中打开网页，而不用默认浏览器(适应Html5)
        webView.getSettings().setDomStorageEnabled(true);
        //webView.getSettings().setMediaPlaybackRequiresUserGesture(false);//
        //允许webview加载js代码
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        //给webview添加js接口(供js调用安卓的方法)
        webView.addJavascriptInterface(new WebAppInterface(this), "android");//js调用安卓


    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_web;
    }


    private WebViewClient mWebViewcLient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Loadingdialog.dismiss();
                        }
                    });
                }
            }, 1000);

        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
        }

    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            LogUtils.i("title:" + title);
            //设置网页标题
            String s = view.getUrl().toString();
            LogUtils.i("当前页面路径:" + s);

            if (!TextUtils.isEmpty(title)) {

                tvTopTitle.setText(title);
            }

        }
    };


    public class WebAppInterface {

        Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }


        //js调用android的方法
        @JavascriptInterface
        public void refreshLogin() {

            // ToastUtils.showLong(content + "");

            String mobile = SPUtils.getInstance().getString(GlobConstant.MOBILE);
            SPUtils.getInstance().clear();
            SPUtils.getInstance().put(GlobConstant.MOBILE, mobile);
            //SPUtils.getInstance().put(GlobConstant.ISSTARTMIAN, true);
            ToastUtils.showLong(getString(R.string.logintimeout));
            // EventBus.getDefault().post(new EventBeans(GlobConstant.FINISHACLLACTIVITY));
            WebActivity.this.finish();
            ActivityUtils.startActivity(WebActivity.this, LoginActivity.class);

        }


        //js调用android的方法
        @JavascriptInterface
        public void jiameng() {
            ActivityUtils.startActivity(SelectTypeActivity.class);
        }

        @JavascriptInterface
        public void setPwd() {

            ActivityUtils.startActivity(EditPwdActivity.class);
        }


        @JavascriptInterface
        public void ajPay(String orderno, final String payment) {
//
            LogUtils.i("订单号:" + orderno);
            LogUtils.i("支付方式:" + payment);


            if (payment.contains("money")) {
                showPaydialog(orderno, payment);
            } else {
                orderPay(orderno, payment);
            }


        }


    }


    private void orderPay(String orderno, final String payment) {
        final String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        OkGo.<String>post(NetUrl.REPAY)
                .params(GlobConstant.TOKEN, token)
                .params("order_no", orderno)
                .params("payment", payment)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("订单支付:" + response.body());

                        try {
                            JSONObject jsonObjects = new JSONObject(response.body());
                            if (jsonObjects.has("code")) {

                                String code = jsonObjects.getString("code");
                                switch (code) {
                                    case GlobConstant.REQUESTSUCCESS:

                                        if (payment.contains("wechat")) {

                                            WxPayBean wxPayBean = GsonUtils.fromJson(response.body(), WxPayBean.class);
                                            WxPayBean.DataBean data = wxPayBean.getData();
                                            if (data != null && !TextUtils.isEmpty(data.getPayinfo())) {
                                                String payinfo = data.getPayinfo();
                                                try {
                                                    JSONObject jsonObject = new JSONObject(payinfo);

                                                    String appid = jsonObject.getString("appid");
                                                    String noncestr = jsonObject.getString("noncestr");
                                                    String packages = jsonObject.getString("package");
                                                    String partnerid = jsonObject.getString("partnerid");
                                                    String prepayid = jsonObject.getString("prepayid");
                                                    String sign = jsonObject.getString("sign");
                                                    String timestamp = jsonObject.getString("timestamp");
                                                    payWechat(appid, partnerid, prepayid, noncestr, timestamp, packages, sign);
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            } else {
                                                ToastUtils.showShort("参数错误");
                                            }

                                        }

                                        if (payment.contains("alipay")) {

                                            AlipayBean alipayBean = GsonUtils.fromJson(response.body(), AlipayBean.class);
                                            AlipayBean.DataBean data = alipayBean.getData();
                                            if (data != null && !TextUtils.isEmpty(data.getPayinfo())) {
                                                String payinfo = data.getPayinfo();
                                                aliPay(payinfo);
                                            } else {
                                                ToastUtils.showShort("参数错误");
                                            }
                                        }

                                        //余额支付
                                        if (payment.equals("money,")) {

                                            ToastUtils.showLong("支付成功");
                                            paySuccess(token);


                                        }
//
//                                        //余额和微信支付
//                                        if (payment.equals("money,wechat")) {
//
//                                            //ToastUtils.showLong("支付成功");
//                                            //paySuccess(token);
//
//                                            showPaydialog("", "wechat");
//                                        }
//
//
//                                        //余额和支付宝支付
//                                        if (payment.equals("money,alipay")) {
//
//                                            showPaydialog("", "alipay");
//                                        }

                                        break;
                                    case GlobConstant.REQUESTERROR:
                                        LoginOutUtils.reLogin(WebActivity.this);
                                        break;
                                    default:
                                        if (jsonObjects.has("msg")) {

                                            ToastUtils.showLong(jsonObjects.getString("msg"));
                                        }

                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.i("订单支付:" + response.code());
                    }
                });
    }

    private void paySuccess(String token) {

        WebActivity.this.finish();
        Intent intent = new Intent(WebActivity.this, WebActivity.class);
        intent.putExtra(GlobConstant.WEBURL, NetUrl.MYORDER + token + "&type=0");
        ActivityUtils.startActivity(intent);


    }

    private static final String[] KEY = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", "<<"};

    private void showPaydialog(final String orderno, final String payment) {
        dialog = new Dialog(this, R.style.bottom_dialog);
        View inflate = View.inflate(this, R.layout.dialog_pay, null);
        dialog.setContentView(inflate);
        Keyboard keyboard = inflate.findViewById(R.id.KeyboardView_pay);
        LinearLayout lldialog2 = inflate.findViewById(R.id.ll_dialog2);
        lldialog2.setVisibility(View.VISIBLE);

        inflate.findViewById(R.id.img_guanbi1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

        inflate.findViewById(R.id.tv_forget_pwd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //忘记密码
                ActivityUtils.startActivity(EditPwdActivity.class);
            }
        });
        keyboard.setKeyboardKeys(KEY);
        final PayEditText payEditText = inflate.findViewById(R.id.PayEditText_pay);
        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {
                if (position < 11 && position != 9) {
                    payEditText.add(value);
                } else if (position == 11) {
                    payEditText.remove();
                } else if (position == 9) {
                }
            }
        }); /**
         *当密码输入完成时的回调
         */
        payEditText.setOnInputFinishedListener(new PayEditText.OnInputFinishedListener() {
            @Override
            public void onInputFinished(String password) {
                //判断密码是否正确
                checkPayWord(password, orderno, payment);
            }
        });
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = AbsListView.LayoutParams.MATCH_PARENT;
        lp.y = 0;
        //设置Dialog距离底部的距离
        dialogWindow.setAttributes(lp);
        dialog.show();
    }


    private void checkPayWord(String password, final String orderno, final String payment) {

        if (!NetworkUtils.isConnected()) {
            ToastUtils.showLong(getString(R.string.neterror));
            return;
        }
        Loadingdialog.show(this);
        String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
        OkGo.<String>post(NetUrl.PWDCHECK)
                .params(GlobConstant.TOKEN, token)
                .params("payword", password)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Loadingdialog.dismiss();
                        LogUtils.i("验证支付密码:" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case GlobConstant.REQUESTSUCCESS://密码验证成功
                                        orderPay(orderno, payment);
                                        break;
                                    case GlobConstant.REQUESTERROR://token过期失效
                                        LoginOutUtils.reLogin(WebActivity.this);
                                        break;
                                    default:
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showLong(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Loadingdialog.dismiss();
                    }
                });
    }


    //支付宝支付
    public void aliPay(final String alipayinfo) {

        LogUtils.i("alipayinfio:" + alipayinfo);

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(WebActivity.this);
                Map<String, String> result = alipay.payV2(alipayinfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    //支付宝支付tag
    public static final int SDK_PAY_FLAG = 1;
    //查询终端设备是否存在支付宝认证账户
    public static final int SDK_CHECK_FLAG = 2;
    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();
                    String result = payResult.getResult();
                    LogUtils.i("resultinfo:" + resultInfo);
                    LogUtils.i("resultStatus:" + resultStatus + payResult.getMemo() + ",result:" + result);
                    final String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtils.showLong("支付成功");


                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                paySuccess(token);
                            }
                        }, 800);


                    } else {

                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtils.showLong("支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtils.showLong("取消支付");
                            LogUtils.i("支付取消");

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    paySuccess(token);
                                }
                            }, 800);


                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtils.showLong("支付失败");
                            LogUtils.i("支付失败");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    paySuccess(token);
                                }
                            }, 800);
                            //EventBus.getDefault().post(new EventBeans(GlobConstant.ALIPAYRESULT));


                        }


                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    ToastUtils.showLong("检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT);
                    break;
                }

            }
        }
    };


    /**
     * 唤起微信支付界面
     */
    protected void payWechat(String appid, String partnerid, String prepayid, String noncestr, String timestamp, String packagevalue, String sign) {
        PayReq req = new PayReq();
        req.appId = appid;
        req.partnerId = partnerid;
        req.prepayId = prepayid;
        req.nonceStr = noncestr;
        req.timeStamp = timestamp;
        req.packageValue = packagevalue;
        req.sign = sign;
        IWXAPI api = WXAPIFactory.createWXAPI(this, appid);
        api.sendReq(req);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wechatPaySuccess(EventBeans eventBean) {

        String code = eventBean.getCode();

        if (code.equals(GlobConstant.WXPAYRESULT)) {
            String msg = eventBean.getMsg();
            LogUtils.i("code:" + code + ",msg:" + msg);
            switch (msg) {
                case GlobConstant.WXPAYSUCCESS:
                case GlobConstant.WXPAYCANCEL:
                case GlobConstant.WXPAYFAILED:
                    //不管支付成功与否,都要跳转页面
                    String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
                    paySuccess(token);
                    break;
                case GlobConstant.WXSHARESUCCESS:
                    //微信分享成功
                    ToastUtils.showLong("分享成功");
                    break;

            }
//            if (TextUtils.equals(GlobConstant.WXPAYSUCCESS, msg)) {
//                //微信支付成功
//                ToastUtils.showLong("微信支付成功");
//
//
//            }

//            if (TextUtils.equals(GlobConstant.WXSHARESUCCESS, msg)) {
//                //微信分享成功
//                ToastUtils.showLong("分享成功");
//            }


        } else if (code.equals(GlobConstant.ALIPAYRESULT)) {
            LogUtils.i("支付宝支付结果");
            String token = SPUtils.getInstance().getString(GlobConstant.TOKEN);
            paySuccess(token);
        }


    }


    @OnClick(R.id.img_back)
    public void onViewClicked() {

        if (!mAgentWeb.back()) {

            finish();
        }
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.clearWebCache();
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
        OkGo.getInstance().cancelAll();

    }
}
